package com.example.module_hp_zao_yin;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.module_hp_zao_yin.activity.HpGongJuSoundActivity;
import com.example.module_hp_zao_yin.activity.MoreRecordsActivity;
import com.example.module_hp_zao_yin.base.BaseMvvmFragment;
import com.example.module_hp_zao_yin.base.BaseViewModel;
import com.example.module_hp_zao_yin.databinding.FragmentHpZaoYinMainBinding;
import com.example.module_hp_zao_yin.entity.HpAudioEntity;
import com.example.module_hp_zao_yin.fragment.HpZaoYinListMainFragment;
import com.example.module_hp_zao_yin.utils.AudioRecordDemo;
import com.fwlst.lib_base.utils.AdUtils;
import com.fwlst.lib_base.utils.JtXXPermissions;
import com.fwlst.lib_base.utils.MmkvUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.maple.recorder.recording.AudioChunk;
import com.maple.recorder.recording.MsRecorder;
import com.maple.recorder.recording.PullTransport;
import com.maple.recorder.recording.Recorder;
import com.maple.recorder.recording.AudioRecordConfig;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;

@Route(path = "/hpZaoYin/route/HpZaoYinMainFragment")
public class HpZaoYinMainFragment extends BaseMvvmFragment<FragmentHpZaoYinMainBinding, BaseViewModel> {
    private AudioRecordDemo audioRecordDemo;
    private List<Double> numArr = new ArrayList<>();//db参数列表，可存储做折线图统计
    Recorder recorder;//录音
    private AudioRecordConfig recordConfig = new AudioRecordConfig();// 参数配置
    private String audioFile = "";//文件路径
    private List<HpAudioEntity> mDataList;//音频地址集合

    @Override
    protected int initLayout() {
        return R.layout.fragment_hp_zao_yin_main;
    }

    @Override
    protected int initBR() {
        return BR.data;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        //点击事件
        binding.startBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermission();
            }
        });
        audioRecordDemo = new AudioRecordDemo(this);
        //监听按钮点击
        viewModel.getCurrentType().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer == 0) return;
                switch (integer) {
                    case 1://点击了结束
                        audioRecordDemo.sotp();
                        if (recorder != null) {
                            recorder.stopRecording(); // 结束
                            recorder = null;
                        }
                        //保存录音地址
                        saveAudioList();
                        break;
                    case 2://点击了开始
                        reset();
                        if (recorder == null) {
                            recorder = getRecorder();
                        }
                        recorder.startRecording();
                        audioRecordDemo.getNoiseLevel(new AudioRecordDemo.MonitorInterface() {
                            @Override
                            public void monitorListener(Double res) {
                                if (res > 0) {
                                    binding.hpZaoYinCv1.setNum(res.floatValue());
                                    numArr.add(res);
                                    setNumArr();
                                }
                            }
                        });
                        break;
                }
            }
        });
        //清零按钮点击
        binding.hpZaoYinMainBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reset();
            }
        });



        addContainerFun();
        binding.tvMore.setOnClickListener(v->{
            navigateTo(MoreRecordsActivity.class);
        });
    }

    private void addContainerFun(){
        binding.flContainer.removeAllViews();
        getChildFragmentManager().beginTransaction().replace(R.id.flContainer, new HpZaoYinListMainFragment()).commit();
    }

    //计算list最大，最小，平均值
    private void setNumArr() {
        Double maxNum = Collections.max(numArr);
        Double minNum = Collections.min(numArr);
        Double sum = 0.0;
        for (Double i : numArr) {
            sum += i;
        }
        Double avNum = sum / numArr.size();
        avNum = Math.round(avNum * 10) / 10.0;
        binding.hpZaoYinTv1.setText(minNum + "dB");
        binding.hpZaoYinTv2.setText(maxNum + "dB");
        binding.hpZaoYinTv3.setText(avNum + "dB");
    }

    //重新开始归零录制
    private void reset() {
        numArr = new ArrayList<>();
        binding.hpZaoYinCv1.setNum(0);
        binding.hpZaoYinTv1.setText(0 + "dB");
        binding.hpZaoYinTv2.setText(0 + "dB");
        binding.hpZaoYinTv3.setText(0 + "dB");
    }

    //开启录音权限
    private void getPermission() {
        List<String> pre = new ArrayList<>();
        pre.add(Manifest.permission.RECORD_AUDIO);
        JtXXPermissions.INSTANCE.requestPermission(requireContext(), "", pre, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                AdUtils.INSTANCE.checkFunction(requireContext(), new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        viewModel.setCurrentType(2);
                        return null;
                    }
                });
                return null;
            }
        });
    }

    //获取普通录音机
    private Recorder getRecorder() {
        //地址设置为内部存储地址
        audioFile = mContext.getFilesDir() + "/" + String.valueOf(new Date().getTime()) + ".wav";
        Log.e("录音文件存储地址：", audioFile);
        // 请确保当前app有 RECORD_AUDIO 权限
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(mContext, "没有 RECORD_AUDIO 权限，无法开始录音～", Toast.LENGTH_SHORT).show();
            return null;
        }
        return MsRecorder.wav(
                new File(audioFile),
                recordConfig,
                // new AudioRecordConfig(MediaRecorder.AudioSource.MIC, AudioFormat.ENCODING_PCM_16BIT, AudioFormat.CHANNEL_IN_MONO, 44100),
                // 普通录音模式
                new PullTransport.Default()
                        .setOnAudioChunkPulledListener(new PullTransport.OnAudioChunkPulledListener() {
                            @Override
                            public void onAudioChunkPulled(AudioChunk audioChunk) {
                                Log.d("数据监听", "最大值 : ${audioChunk.maxAmplitude()} ");
                                //animateVoice((float) (audioChunk.maxAmplitude() / 200.0));
                            }
                        })
        );
    }

    //保存音频地址到本地
    private void saveAudioList() {
        String listStr = MmkvUtils.INSTANCE.get("mAudioList", "");
        Type typeToken = new TypeToken<List<HpAudioEntity>>() {
        }.getType();
        //将list集合反序列化
        mDataList = new Gson().fromJson(listStr, typeToken);
        if (mDataList == null) {
            mDataList = new ArrayList<>();
        }
        int p = -1;
        for (HpAudioEntity item : mDataList) {
            if (item.getPath().equals(audioFile)) {
                p = 1;
                break;
            }
        }
        if (p < 0) {
            mDataList.add(0, new HpAudioEntity(
                    audioFile,
                    new Gson().toJson(numArr),
                    binding.hpZaoYinTv1.getText().toString(),
                    binding.hpZaoYinTv2.getText().toString(),
                    binding.hpZaoYinTv3.getText().toString()
            ));
        }
        //将list集合序列化
        listStr = new Gson().toJson(mDataList);
        MmkvUtils.INSTANCE.save("mAudioList", listStr);
        addContainerFun();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        audioRecordDemo.sotp();
    }
}